/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-03-25
 * Time: 14:03
 */
public class myLinkedList<T> {

    /**
     * 结点类
     */
    static class Node {
        Object val;
        Node next;

        public Node(Object val) {
            this.val = val;
        }
    }

    public Node head;//头结点(第一个结点)


    /**
     * 尾插数据
     *
     * @param val 要插入的数据
     */
    public void add(T val) {

        Node newNode = buyNode(val);
        if (head == null) {
            head = newNode;
            return;
        }
        Node tail = head;
        //找尾巴
        while (tail.next != null) {
            tail = tail.next;
        }
        tail.next = newNode;
    }

    /**
     * 头插
     *
     * @param val 要插入的数据
     */
    public void addFront(T val) {
        Node newNode = buyNode(val);
        if (head == null) {
            head = newNode;
            return;
        }
        newNode.next = head;
        head = newNode;
    }

    /**
     * @param pos 下标
     * @param val 值
     */

    public void addIndex(int pos, T val) {
        try {
            if (pos < 0 || pos > getSize()) {
                throw new IndexNotLegalException("下标不合法");
            }
        } catch (IndexNotLegalException e) {
            e.printStackTrace();
        }
        Node newNode = buyNode(val);
        Node cur = head;
        if (pos == 0) {
            addFront(val);
            return;
        }
        if (pos == getSize()) {
            add(val);
            return;
        }

    }

    public int getSize() {
        int count = 0;
        Node cur = head;
        while (cur != null) {
            count++;
            cur = cur.next;
        }

        return count;
    }

    /**
     * 打印链表
     */
    public void display() {
        Node cur = head;
        System.out.print("[");
        while (cur != null) {
            System.out.print(cur.val);
            if (cur.next != null) {
                System.out.print(",");
            }
            cur = cur.next;
        }
        System.out.println("]");
    }

    /**
     * 申请结点
     *
     * @param val 结点的数据
     * @return 返回这个结点
     */
    private Node buyNode(T val) {
        return new Node(val);
    }
}
